/* 
 -----------------------------------------------------------------------------
                   Cogaen - Component-based Game Engine (v3)
 -----------------------------------------------------------------------------
 This software is developed by the Cogaen Development Team. Please have a 
 look at our project home page for further details: http://www.cogaen.org
    
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Copyright (c) 2010 Roman Divotkey

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/

package org.cogaen.java2d;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import org.cogaen.core.Core;
import org.cogaen.core.Service;
import org.cogaen.name.NameService;
import org.cogaen.resource.ResourceManager;

public class SceneManager implements Service {

	/** Unique name of this service. */	
	public static final String NAME = "cogaen.scenemanager";

	/** Used for logging messages generated by this service */
	public static final String LOGGING_SOURCE = "SceneManager";
	
	private static final boolean DEFAULT_HIGH_QUALITY = true;
	private Stack<AffineTransform> transformStack = new Stack<AffineTransform>();
	private Map<String, SceneNode> namedNodes = new HashMap<String, SceneNode>();
	private Map<String, Camera> cameras = new HashMap<String, Camera>();
	private LinkedHashMap<String, Overlay> overlays = new LinkedHashMap<String, Overlay>();
	private List<Force> forces = new ArrayList<Force>();
	private SceneNode rootNode;
	private Core core;
	
	private Screen screen;
	private boolean clearBackground = false;
	private Color backgroundColor = Color.BLACK;
	private Color forceColor = Color.RED;
	private double forceWidth = 0.1;
	private boolean highQuality = DEFAULT_HIGH_QUALITY;;
	private double forceScale = 1.0;

	private int mask;
	
	public SceneManager(Screen screen) {
		this.screen = screen;
		this.rootNode = createSceneNode("root");
	}
	
	public Screen getScreen() {
		return this.screen;
	}

	public boolean isHighQuality() {
		return this.highQuality;
	}
	
	public void setHighQuality(boolean value) {
			this.highQuality  = value;
	}
	
	public boolean getHighQuality() {
		return this.highQuality;
	}
	
	public void setClearBackground(boolean value) {
		this.clearBackground = value;
	}
	
	public double getForceScale() {
		return this.forceScale;
	}
	
	public void setForceScale(double forceScale) {
		this.forceScale = forceScale;
	}
	
	public boolean isClearBackground() {
		return this.clearBackground;
	}
	
	public void setBackgroundColor(Color color) {
		this.backgroundColor = color;
	}
	
	public Camera createCamera(String name) {
		if (name == null) {
			throw new NullPointerException("parameter name must not be null");
		}
		
		Camera camera = new Camera(name, this.screen.getWidth(), this.screen.getHeight());
		Camera oldCamera = this.cameras.put(name, camera);
		if (oldCamera != null) {
			this.cameras.put(name, oldCamera);
			throw new RuntimeException("camera with name '" + name + "' already exists");
		}
		
		return camera;
	}
	
	public Camera createCamera() {
		return createCamera( NameService.getInstance(core).generateName() );
	}
	
	public void destroyCamera(Camera camera) {
		if (camera != null) {
			this.cameras.remove(camera);
		}
	}
	
	public void destroyCamera(String name) {
		destroyCamera(getCamera(name));
	}
	
	public void destroyAllCameras() {
		this.cameras.clear();
	}
	
	private Camera getCamera(String name) {
		return this.cameras.get(name);
	}

	public SceneNode getRootSceneNode() {
		return this.rootNode;
	}
	
	public SceneNode createSceneNode() {
		return createSceneNode( NameService.getInstance(core).generateName() );
	}
	
	public SceneNode createSceneNode(String name) {		
		if (name == null) {
			throw new NullPointerException("parameter name must not be null");
		}
		
		SceneNode node = new SceneNode(name);
		SceneNode oldNode = this.namedNodes.put(name, node);
		if (oldNode != null) {
			this.namedNodes.put(name, oldNode);
			throw new RuntimeException("scene node with name '" + name + "' already exists");
		}
		
		return node;
	} 
	
	public void destroySceneNode(SceneNode node) {
		if (node == this.rootNode) {
			throw new RuntimeException("root scene node can't be destroyed"); 
		}
		
		destroySceneNode(this.rootNode, node);		
		this.namedNodes.remove(node.getName());
	}
	
	public void destroySceneNode(String name) {
		SceneNode node = this.namedNodes.get(name);
		if (node != null) {
			destroySceneNode(node);
		}
	}
	
	public SceneNode getSceneNode(String name) {
		return this.namedNodes.get(name);
	}
	
		
	public void addForce(double px, double py, double vx, double vy) {
		this.forces.add(new Force(px, -py, vx * this.forceScale, -vy * this.forceScale));
	}
	
	private boolean destroySceneNode(SceneNode parent, SceneNode nodeToDestroy) {
		if (parent.getChildren() == null) {
			return false;
		}
		
		for(Iterator<SceneNode> it = parent.getChildren().iterator(); it.hasNext(); ) {
			SceneNode child = it.next();
			
			if (child == nodeToDestroy) {
				it.remove();
				return true;
			}
			
			if (destroySceneNode(child, nodeToDestroy)) {
				return true;
			}
		}
		
		return false;
	}
	
	
	public void renderScene() {
		Graphics2D g = this.screen.getGraphicsContext();
		if (this.clearBackground) {
			g.setColor(backgroundColor);
			g.fillRect(0, 0, screen.getWidth(), screen.getHeight());
		}
		
		if (this.highQuality) {
			g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);			
			g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
		} else {
			g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
			g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
			g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);			
		}
		
		// render visuals
		for (Camera camera : this.cameras.values()) {
			// apply camera clipping area
			Viewport viewport = camera.getViewport();
			Shape clip = g.getClip();
			g.setClip(viewport.getX(), viewport.getY(), viewport.getWidth(), viewport.getHeight());
			
			// apply camera transform
			this.transformStack.push(g.getTransform());
			g.transform(camera.getTransform());
			
			// set current camera/visual mask
			this.mask = camera.getMask();
			
			// render scene graph
			renderNode(this.rootNode, g);
			
			// render forces (experimental)
			g.setColor(this.forceColor);
			g.setStroke(new BasicStroke((float) this.forceWidth));
			for (Force force : this.forces) {
				g.draw(new Line2D.Double(force.x1, force.y1, force.x2, force.y2));
			}
			this.forces.clear();
			
			// restore transform
			g.setTransform(this.transformStack.pop());
			g.setClip(clip);
		}
		
		// render overlays
		for (Overlay overlay : this.overlays.values()) {
			renderOverlay(overlay, g);
		}
		g.dispose();
		
		this.screen.update();
	}
	
	public void centerOverlay(Overlay overlay) {
		overlay.setPosition(this.screen.getWidth() / 2, this.screen.getHeight() / 2);
	}
	
	public void centerOverlay(String name) {
		centerOverlay(getOverlay(name));
	}
	
	private void renderOverlay(Overlay overlay, Graphics2D g) {
		g.setTransform(overlay.getTransform());
		for (Visual visual : overlay.getVisuals()) {
			visual.render(g);
		}
	}

	private void renderNode(SceneNode node, Graphics2D g) {
		// apply transform
		this.transformStack.push(g.getTransform());
		g.transform(node.getTransform());
				
		// render all visuals attached to this node
		for (Visual visual : node.getVisuals()) {
			if (visual.isVisible(this.mask)) {
				visual.render(g);
			}
		}
						
		// render children
		List<SceneNode> children = node.getChildren();
		if (children != null) {
			for (SceneNode child : children) {
				renderNode(child, g);
			}
		}
		
		// restore transform
		g.setTransform(this.transformStack.pop());
	}
	
	public RectangleVisual createRectangleVisual(double w, double h) {
		return new RectangleVisual(w, h);		
	}
	
	public CircleVisual createCircleVisual(double radius) {
		return new CircleVisual(radius);
	}
	
	public Visual createPolygonVisual(String resourceName) {
		Polygon poly = (Polygon) ResourceManager.getInstance(this.core).getResource(resourceName);
		return new PolygonVisual(poly);
	}
	
	public Visual createPolygonVisual(Polygon poly) {
		return new PolygonVisual(poly);		
	}
		
	public Overlay createOverlay(String name) {
		if (name == null) {
			throw new NullPointerException("parameter name must not be null");
		}
		
		Overlay overlay = new Overlay(name);
		Overlay oldOverlay = this.overlays.put(name, overlay);
		if (oldOverlay != null) {
			this.overlays.put(name, oldOverlay);
			throw new RuntimeException("Overlay with name '" + name + "' already exists");
		}
		
		return overlay;
	}

	public Overlay createOverlay() {
		return createOverlay(NameService.getInstance(core).generateName());
	}
	
	public Overlay getOverlay(String name) {
		return this.overlays.get(name);
	}
	
	public void destroyOverlay(Overlay overlay) {
		Overlay oldOverlay = this.overlays.remove(overlay.getName());
		assert(oldOverlay == overlay);
	}
	
	public void destroyOverlay(String name) {
		this.overlays.remove(name);
	}
	
	public void destroyAllOverlays() {
		this.overlays.clear();
	}
		
	/**
	 * Returns the overlay at the given screen position, which is needed to determine which item was selected at a mouse press.
	 * @param x		X positions in screen coordinates.
	 * @param y		Y positions in screen coordinates.
	 * @return	Returns the selected Overlay (the top most one) if anyone was selected, otherwise null.
	 */
	public Overlay getOverlayAtScreenPosition(int x, int y) {
	
		Collection<Overlay> c = overlays.values();
		Overlay[] overlayArray = new Overlay[c.size()];
		c.toArray(overlayArray);
		
		// the overlays have to be checked from the last element (which is the top most one) to the one which is below!
		for(int i=c.size()-1; i>=0; i--) {
			Overlay o = overlayArray[i];
			if(o.contains(x, y))
				return o;
		}
		return null;
	}
		
	@Override
	public String getName() {
		return NAME;
	}
	
	@Override
	public void initialize(Core core) {
		this.core = core;
	}

	public static SceneManager getInstance(Core core) {
		return (SceneManager) core.getService(NAME);
	}

	public void destroyAllSceneNodes() {
		getRootSceneNode().getVisuals().clear();
		
		if (this.rootNode.getChildren() == null) {
			return;
		}
		
		while (!this.rootNode.getChildren().isEmpty()) {
			destroySceneNode( this.rootNode.getChildren().get(this.rootNode.getChildren().size() - 1) );
		}
	}

	public Component getComponent() {
		return this.screen.getComponent();
	}

	/**
	 * Destroys all elements within in this scene.
	 * 
	 * <p>
	 * Calling this method is equivalent to:
	 *  
	 * <pre>
	 * destroyAllCameras();
	 * destroyAllOverlays();
	 * destroyAllSceneNodes();
	 * </pre>
	 * </p>
	 */
	public void destroyAll() {
		destroyAllCameras();
		destroyAllOverlays();
		destroyAllSceneNodes();
	}
	
	
	private static class Force {
		private double x1, x2, y1, y2;
		public Force(double px, double py, double vx, double vy) {
			this.x1 = px;
			this.y1 = py;
			this.x2 = px + vx;
			this.y2 = py + vy;
			Math.sqrt(vx * vx + vy * vy);
		}
		
	}

	public Visual loadVisual(String resName) {
		return (Visual) ResourceManager.getInstance(this.core).getResource(resName);
	}

	public int numOfNodes() {
		return this.namedNodes.size();
	}

}
